package com.hs.pre;

import static org.apache.solr.request.SolrParams.ROWS;
import static org.apache.solr.request.SolrParams.START;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.Query;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrException;
import org.apache.solr.request.QueryResponseWriter;
import org.apache.solr.request.SolrParams;
import org.apache.solr.request.SolrQueryResponse;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.request.XMLWriter;
import org.apache.solr.search.DocListAndSet;
import org.apache.solr.search.QueryParsing;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.servlet.SolrServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.hs.core.action.BaseAction;
import com.hs.log.HsLogger;
import com.hs.pre.model.PreEntry;
import com.hs.pre.model.ProfileBean;
import com.hs.pre.module.data.FjPreCache;
import com.hs.pre.sys.validate.ParameterDic;
import com.hs.utils.ParseXml;

public class SearchAction extends BaseAction {
	SolrCore core;
	private static final HsLogger logger = HsLogger
			.getLogger(SearchAction.class.getName());
	
	/**
	 * 查询结果默认记录数
	 */
	private int MAX_RETURN_NUM = 10;

	public void init() throws ServletException {
		core = SolrCore.getSolrCore();
		logger.config("init");
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		init();
		request.setCharacterEncoding("utf-8");
		/**************
		 *通过分类快捷方式进入查询页面
		 *找出该分类下面的所有方剂id
		 *
		 */
		String fjIdStr = "";
		if (request.getParameter("sortId") != null
				&& !"".equals(request.getParameter("sortId"))) {
			FjPreCache sortCache = FjPreCache.getInstance();
			fjIdStr = sortCache.getPreStrId(new Long(request.getParameter(
					"sortId").toString()));
			request.setAttribute("sortId", request.getParameter("sortId")
					.toString());
		}
		/****************/

		SolrServletRequest solrReq = new SolrServletRequest(core, request);
		SolrQueryResponse solrRsp = new SolrQueryResponse();
		String q = request.getParameter("q");
		String newQ = "";
		if (q != null && !(q = q.trim()).equals(""))
			newQ = "(id:" + q + ")";
		if (fjIdStr != "") {
			if (!newQ.equals(""))
				newQ += " AND ";
			newQ += "(" + fjIdStr + ")";
		}
		SolrParams p = solrReq.getParams();
		this.setBardianPageNumber(request, p);
		
		logger.info("fq is " + p.get("fq") + " new Q is " + newQ);
		DocListAndSet results = new DocListAndSet();
		Query query = QueryParsing.parseQuery(newQ, "", p, solrReq.getSchema());
		SolrIndexSearcher s = solrReq.getSearcher();
		results.docList = s.getDocList(query, null, null, p.getInt(START, 0),MAX_RETURN_NUM,0);
		solrRsp.add("results", results.docList);

		//		    SolrServletRequest solrReq = new SolrServletRequest(core, request);;
		//		    SolrQueryResponse solrRsp = new SolrQueryResponse();		    
		try {
			//
			//		      SolrRequestHandler handler = core.getRequestHandler(solrReq.getQueryType());
			//		      if (handler==null) {
			//		    	  logger.warning("Unknown Request Handler '" + solrReq.getQueryType() +"' :" + solrReq);
			//		        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,"Unknown Request Handler '" + solrReq.getQueryType() + "'", true);
			//		      }
			//		      core.execute(handler, solrReq, solrRsp );
			if (solrRsp.getException() == null) {
				QueryResponseWriter responseWriter = core
						.getQueryResponseWriter(solrReq);
				StringWriter out = new StringWriter();
				XMLWriter.writeResponse(out, solrReq, solrRsp);
				ParseXml parse = new ParseXml(out.getBuffer().toString());
				List docList = parse.getDoc();
				List entryList = new ArrayList();
				for (int i = 0; i < docList.size(); i++) {
					PreEntry entry = new PreEntry((Map) docList.get(i));
					entryList.add(entry);
				}
				request.setAttribute("resultDoc", entryList);
				request.setAttribute("params", parse.getLst());
				request.setAttribute("resultNum", parse.getNumFound() + "");
				String start = request.getParameter("start");
				request.setAttribute("start", start);
				//每页显示的数量，暂时写死10个，正式发布版本应该根据用户定义的数量来显示，默认显示为20
				int pageNum = 10;
				request.setAttribute("pageNum", pageNum + "");

				try {
					Integer startNum = 1;
					if (null != request.getParameter("start")
							&& !"".equals(request.getParameter("start"))) {
						startNum = new Integer(request.getParameter("start")) + 1;
					}
					request.setAttribute("startNum", startNum.toString());
					Integer end = startNum + pageNum - 1;
					request.setAttribute("endNum", end.toString());
				} catch (NumberFormatException ex) {
					request.setAttribute("endNum", pageNum);
				}

				//参数串
				StringBuilder builder = new StringBuilder("");
				String paramStr = request.getParameter("q");
				String fqParam = request.getParameter("fq");
				if(paramStr != null)
				builder.append(paramStr);
				if (StringUtils.isNotBlank(fqParam)) {
					builder.append(" AND ");
					builder.append(fqParam);
				}
				request.setAttribute("paramStr", builder.toString());
				logger.info("paramStr is " + paramStr + " builder:"
						+ builder.toString());
			} else {
				Exception e = solrRsp.getException();
				int rc = 500;
				if (e instanceof SolrException) {
					rc = ((SolrException) e).code();
				}
				sendErr(rc, SolrException.toStr(e), request, response);
			}
		} catch (SolrException e) {
			if (!e.logged)
				logger.info(e.getMessage());
			sendErr(e.code(), SolrException.toStr(e), request, response);
		} catch (Throwable e) {
			logger.info(e.getMessage());
			sendErr(500, SolrException.toStr(e), request, response);
		} finally {
			// This releases the IndexReader associated with the request
			solrReq.close();
		}

		String searchType = request.getParameter("type");
		String forward = "result";
		if ("simila".equals(searchType)) {
			forward = "simila";
		}
		return mapping.findForward(forward);
	}

	
	/****
	 *   设置个性化显示每页行数<br>
	 *   当用户没登录时采取默认行数,但是页面有rows参数 就以页面传入参数为准<br>
	 *   如果登录了就以个性化设置为准 <br>
	 * 
	 * @param request
	 * @param p
	 */
	private void setBardianPageNumber(HttpServletRequest request,SolrParams p)
	{
		 MAX_RETURN_NUM = p.getInt(ROWS,MAX_RETURN_NUM);
		 ProfileBean profileBean = (ProfileBean)request.getSession().getAttribute(ParameterDic.USER_BARDIAN);
		 if(profileBean != null)
		 { 
			 MAX_RETURN_NUM = profileBean.getViewNum();
		 }
		
	}

	
	
	final void sendErr(int rc, String msg, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// hmmm, what if this was already set to text/xml?
			try {
				response
						.setContentType(QueryResponseWriter.CONTENT_TYPE_TEXT_UTF8);
				// response.setCharacterEncoding("UTF-8");
			} catch (Exception e) {
			}
			try {
				response.setStatus(rc);
			} catch (Exception e) {
			}
			PrintWriter writer = response.getWriter();
			writer.write(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
